<template>
  <div class="parent-child-demo">
    <h1>父子组件演示</h1>

    <div class="demo-grid">
      <div class="demo-card">
        <h2>父组件区域</h2>
        <ParentComponent />
      </div>

      <div class="demo-card">
        <h2>子组件信息</h2>
        <div class="desc">展示子组件的 props、作用域插槽与交互</div>
        <ChildComponent :message="demoMessage" :count="demoCount" @parent-demo-event="handleParentDemoEvent">
          <template #default="{ parentData, parentMethod }">
            <p>props.message：{{ demoMessage }}</p>
            <p>props.count：{{ demoCount }}</p>
            <p>slot.parentData：{{ parentData }}</p>
            <button class="action-btn" @click="parentMethod">调用子组件方法</button>
          </template>
        </ChildComponent>
        <p>子组件向父组件发送事件：{{ parentDemoMessage }}</p>
      </div>
    </div>
  </div>
  <ChildComponent ref="childRef"></ChildComponent> 
  <button @click="callChildMethod">调用子组件方法,使用ref</button>
  
</template>

<script setup>
import { provide, ref } from 'vue'
import ParentComponent from '../components/ParentComponent.vue'
import ChildComponent from '../components/ChildComponent.vue'

const demoMessage = ref('我是demo，冒充父组件发送props消息')
const demoCount = ref(42)

const parentDemoMessage = ref('');

function handleParentDemoEvent(msg) {
    parentDemoMessage.value = msg;
}

const injectedData = "我是祖先组件，我要给后代组件inject数据，这样可以实现祖先组件向所有后代组件的传递!"
provide('sharedData', injectedData);

const childRef = ref(null);

// 调用子组件方法
function callChildMethod() {
    if (childRef.value) {
        childRef.value.childMethod();
    }
}


</script>

<style scoped>
.parent-child-demo {
  padding: 20px;
}
.parent-child-demo h1 {
  margin-bottom: 16px;
}
.demo-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}
.demo-card {
  padding: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #fff;
}
.demo-card h2 {
  margin: 0 0 8px 0;
}
.desc {
  margin-bottom: 8px;
  color: #6b7280;
}
.action-btn {
  margin-top: 8px;
  padding: 6px 10px;
  border-radius: 6px;
  background: #10b981;
  color: #fff;
}
</style>